import os, sqlite3, time
from CoreFunctions import FindMovieImage
from CoreFunctions import LogEvents, LogEvent

class MovieClass():
    def __init__(self):
        self.Mode           = 1
        self.DBName         = ""
        self.MovieFolder    = ""
        self.Title          = ""
        self.ID             = ""
        self.Actors         = {}
        self.NFO            = ""
        self.NFODate        = ""
        self.MoviePath      = ""
        self.Year           = ""
        self.ReleaseDate    = ""
        self.Rating         = ""
        self.Votes          = ""
        self.Outline        = ""
        self.Plot           = ""
        self.Tagline        = ""
        self.MPAA           = ""
        self.Certification  = ""
        self.Release        = ""
        self.Studio         = ""
        self.Country        = ""
        self.Language       = ""
        self.Genre          = ""
        self.Credits        = ""
        self.Director       = ""
        self.Country        = ""
        self.LogFile        = ""
        self.FanArt         = ""
        self.Cover          = ""
        self.VideoCODEC     = ""
        self.VideoAspect    = ""
        self.VideoWidth     = ""
        self.VideoHeight    = ""
        self.AudioCODEC     = ""
        self.AudioChannels  = ""
        
        try:
            SQL = "UPDATE tblMovies SET flag=9"
            #self.cursor = self.cn.execute(SQL)
        except Exception, x:
            LogEvent(x)
    

                   
                
    def Connect(self):
        self.cn = sqlite3.connect(self.DBName)
            
    def LoadSettings(self, appdir, inifile):
        """
        This def opens an ini file and loads the settings from within it.
        Accepts    : The path and name of an ini file.
        Returns    : The path to the base upload file, or False if an error occurs.
        """
    
        
        try:
            if GetConfig(inifile):
                pass
            else:
                return False
        except Exception, x:
            
            return False

    
        
    def CheckForMovie(self, MoviePath):
        try:    
            LogEvent("CheckForMovie: Checking the database for movie " + MoviePath)
            SQL = "SELECT MoviePath from tblMovies WHERE MoviePath = '%s'" % MoviePath
        
            self.cursor = self.cn.execute(SQL)
            rows = self.cursor.fetchall()
            
            if rows:
                try:
                    #SQL = "UPDATE tblMovies SET Flag=0 WHERE MoviePath = '%s'" % MoviePath
                    #self.cursor = self.cn.execute(SQL)
                    LogEvent("Movie found in datavase")
                    return True
                
                except Exception, x:
                    LogEvent(x) 
            else:
                LogEvent("Movie NOT found in database")
                return False
                     
            self.cursor = None
                       
        except Exception, x:
            LogEvent(x)
            
    def CompareNFODate(self):
        try:
            LogEvent("CompareNFODate: Comparing the file date against the date in the database...")
            SQL = "SELECT nfodate from tblMovies WHERE IMDBID = '%s'" % self.ID
        
            self.cursor=self.cn.execute(SQL)
            self.rows = self.cursor.fetchall()
            if self.rows:
                #we have a record
                LogEvent("NFO found")
                for self.row in self.rows:
                    try:
                        if self.row[0]!=self.NFODate:
                            LogEvent("The dates are different")
                            return False
                        else:
                            LogEvent("The dates are the same")
                            return True
                         
                    except Exception, x:
                        LogEvent(x)
            else:
                LogEvent("No NFO found")
                return False
                        
            self.cursor = None
            
        except Exception, x:
            LogEvent(x)

    def UpdateMovie(self):
        try:
            LogEvent("UpdateMovie: Updating entry in database...")
            #but the NFO date is different to what we have recorded...
            SQL = 'UPDATE tblMovies SET moviepath="%s", title="%s", rating="%s", votes="%s", outline="%s", plot="%s", tagline="%s", mpaa="%s", certification="%s", ' \
              'release="%s", studio="%s", country="%s", language="%s", genre="%s", credits="%s", director="%s", nfo="%s", nfodate="%s", ' \
              'year = "%s", releasedate="%s", flag=0, studio="%s", MovieCover="%s", MovieFanart="%s" , VideoCODEC = "%s", VideoAspect="%s", VideoWidth="%s", '\
                  'VideoHeight="%s", AudioCODEC="%s", AudioChannels="%s" '\
              'WHERE IMDBID = "%s"' % (self.MoviePath, self.Title, self.Rating, self.Votes, self.Outline, self.Plot, self.Tagline, self.MPAA, \
                                       self.Certification, self.Release, self.Studio, self.Country, self.Language, self.Genre, self.Credits, self.Director, \
                                       self.NFO, self.NFODate, self.Year, self.ReleaseDate, self.Studio, self.Cover, self.FanArt, self.VideoCODEC, \
                                       self.VideoAspect, self.VideoWidth, self.VideoHeight, self.AudioCODEC, self.AudioChannels, self.ID)                                        
        #SQL = SQL.replace("'", "''")
        
        
            LogEvent(SQL)
            self.cursor = self.cn.execute(SQL)
            self.cursor = None
            self.cn.commit()
        except Exception, x:
            LogEvent(x)
    
    def InsertMovie(self):
        try:
            LogEvent("InsertMovie: Inserting entry into database...")
            SQL = 'INSERT into tblMovies (imdbid, moviepath, title, rating, votes, outline, plot, tagline, mpaa, certification, release, studio, country, language, genre, ' \
                  'credits, director, nfo, nfodate, year, releasedate, flag, studio, MovieCover, MovieFanart, VideoCODEC, VideoAspect, VideoWidth, '\
                  'VideoHeight, AudioCODEC, AudioChannels) ' \
                  'VALUES("%s", "%s","%s", "%s","%s", "%s","%s", "%s","%s", "%s","%s", "%s","%s", "%s","%s", "%s","%s", "%s","%s", "%s", "%s", 0, "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")' % (self.ID, self.MoviePath, \
                  self.Title, self.Rating, self.Votes, self.Outline, self.Plot, self.Tagline, self.MPAA, self.Certification, self.Release, \
                  self.Studio, self.Country, self.Language, self.Genre, self.Credits, self.Director, self.NFO, self.NFODate, self.Year, \
                  self.ReleaseDate, self.Studio, self.Cover, self.FanArt, self.VideoCODEC, self.VideoAspect, self.VideoWidth, self.VideoHeight, \
                  self.AudioCODEC, self.AudioChannels)
        #SQL = SQL.replace("'", "''")    
            LogEvent(SQL)
            self.cursor = self.cn.execute(SQL)
            self.cn.commit()
            self.cursor = None
            
        except Exception, x:
            LogEvent(x)
            
    def Submit(self):
        #check for the main movie information
        if self.CheckForMovie(self.MoviePath)==True:                 #the movie is in the database
            Update = False
            if self.Mode != 1:          #if the mode is not update mode then update every movie
                LogEvent( " - updating movie...%s" % (self.Title))  
                self.FanArt     = FindMovieImage(self.MoviePath, "F")
                self.Cover      = FindMovieImage(self.MoviePath, "C")
                self.UpdateMovie()
                self.GetActors()
            else:    
                if self.NFO!=False:                                 #is there an NFO in the db?               
                    if self.CompareNFODate() == True:               #compare the NFO file date against the db date
                        LogEvent( " - the NFO date is the same")
                    else:                                           #the dates are different, update the db
                        LogEvent( " - updating movie...%s" % (self.Title))  
                        self.FanArt = FindMovieImage(self.MoviePath, "F")
                        self.Cover  = FindMovieImage(self.MoviePath, "C")
                        self.UpdateMovie()
                        self.GetActors()
                else:                                               #there is a movie, but no NFO - update the db
                    LogEvent( " - updating movie...%s" % (self.Title))
                    self.FanArt = FindMovieImage(self.MoviePath, "F")
                    self.Cover  = FindMovieImage(self.MoviePath, "C")
                    self.UpdateMovie()
                    self.GetActors()
                    
        else:                                                   #there is no movie - add it to the db
            LogEvent( " - adding movie...%s" % (self.Title))
            self.FanArt = FindMovieImage(self.MoviePath, "F")
            self.Cover  = FindMovieImage(self.MoviePath, "C")
            self.InsertMovie()
            self.GetActors()
            
    def UpdateActorThumb(self, ActorID, ActorThumb ):
        try:
            LogEvent("UpdateActorThumb: Adding thumbnail...")
            SQL = "UPDATE tblActors SET ActorThumb = '%s' WHERE ActorID = %i" % (ActorThumb, ActorID)
            self.cursor = self.cn.execute(SQL)
            self.cn.commit()
            
        except Exception, x:
            LogEvent( x)
    
    def GetActorID(self, ActorFirstName, ActorLastName):
        try:
            ActorFirstName  = unicode(ActorFirstName)
            ActorLastName   = unicode(ActorLastName)
            LogEvent("GetActorID: Retrieving ID for '%s %s' " % (ActorFirstName, ActorLastName ))
            SQL = "SELECT ActorID from tblActors WHERE ActorFirstName = '%s' AND ActorLastName = '%s'" % (ActorFirstName.replace("'", "''"), ActorLastName.replace("'", "''"))
            self.cursor = self.cn.execute(SQL)
            rows = self.cursor.fetchall()
            if rows:
                LogEvent("Actor found")
                for row in rows:
                    return row[0]
                    break
            else:
                LogEvent(SQL)
                LogEvent(" - actor found") 
            
        except Exception, x:
            LogEvent(x)
            return None
         
    def AddActor(self, ActorFirstName, ActorLastName):    
        if type(ActorLastName)==type(list()):
            LastName = ""
            for Name in ActorLastName:
                LastName+=Name
        else:
            LastName = ActorLastName
        LogEvent("AddActor: Adding actor '%s %s'" % (ActorFirstName, ActorLastName))    
        SQL = "INSERT INTO tblActors (ActorFirstName, ActorLastName) VALUES ('%s', '%s')" % (ActorFirstName.replace("'", "''"), LastName.replace("'", "''"))
        try:
            self.cursor = self.cn.execute(SQL)
            self.cn.commit()
            return self.GetActorID(ActorFirstName, ActorLastName)
        except Exception, x:
            LogEvent( x)
            
    def HasMovieRole(self, ActorID, ActorRole):
            LogEvent("HasMovieRole: Checking ActorID '%s' for role '%s'" % (ActorID, ActorRole))
            SQL = "SELECT ActorRole from tblMovieActors WHERE MovieID='%s' AND ActorID='%s' AND ActorRole='%s'" % (self.ID, ActorID, ActorRole.replace("'", "''"))
            try:
                self.cursor=self.cn.execute(SQL)
                rows = self.cursor.fetchall()
                if rows:
                    LogEvent(" - role found")
                    return True
                else:
                    LogEvent(" - role not found")
                    return False
            
            except Exception ,x:
                LogEvent( x)
                
    def AddActorRole(self, ActorID, ActorRole):
        LogEvent("AddActorRole: Adding movie role '%s' to actorID '%s'" % (ActorRole, ActorID))
        SQL = "INSERT into tblMovieActors (MovieID, ActorID, ActorRole) VALUES ('%s', '%s', '%s')" % (self.ID, ActorID, ActorRole.replace("'", "''"))
        try:
            self.cursor = self.cn.execute(SQL)
            self.cn.commit()
            
        except Exception, x:
            LogEvent(x)
                
    def GetActors(self):
        LogEvent("GetActors: Building list of actors from NFO file")
        for Actor in self.Actors.keys():
            try:
                ActorID         = ""
                ActorName       = Actor.split(' ')
                ActorFirstName  = ActorName[0]
                ActorLastName   = ""
                ActorThumb      = ""
                if len(ActorName)>0:
                    try:
                        for Name in ActorName[1:]:
                        #        ActorLastName += Name + " "
                        #else:
                            ActorLastName += Name + " "
                                    
                    except IndexError:
                        ActorLastName = ""   
                LogEvent(" - actor name is '%s %s'" % (ActorFirstName, ActorLastName))         
                ActorID = self.GetActorID(ActorFirstName, ActorLastName)
 
            except Exception, x:
                LogEvent( x)

            if ActorID==None:
                ActorID = self.AddActor(ActorFirstName, ActorLastName)
                    
            ActorThumb = ""
            for roles in self.Actors[Actor]:
                if "http://" in roles:
                    self.UpdateActorThumb(ActorID, unicode(roles))
                else:
                    if self.HasMovieRole(ActorID, roles)==False:
                        self.AddActorRole(ActorID, roles)   
            LogEvent("\n\n")          